#include "UserChatWindow.hpp"
#include "LoginWindow.hpp"
#include "UsersRegister.hpp"
#include "tools/Logger.hpp"
#include "tools/ReadAndWeite.hpp"
#include <QApplication>
#include <QColor>
#include <QDateTime>
#include <QDebug>
#include <QFileDialog>
#include <QFont>
#include <QInputDialog>
#include <QLineEdit>
#include <QMessageBox>
#include <QPainter>
#include <QPixmap>
#include <QScrollBar>
#include <QStyle>
#include <QTextBrowser>
#include <QTimer>
#include <QUuid>
#include <iostream>
#include <qdebug.h>
#include <string>

// 统一定义样式常量
namespace Style {
const QString WINDOW = "background-color: #f5f5f5;";
const QString LEFT_CONTAINER = "background-color: #EEEEEE; border: 0.5px solid "
                               "#D0D0D0; border-radius: 4px;";
const QString TITLE =
    "font-size: 20px; font-weight: bold; color: #343541; padding: 10px;";
const QString NEW_CHAT_BUTTON =
    "QPushButton { background-color: #10a37f; color: white; border-radius: "
    "5px; font-weight: bold; }"
    "QPushButton:hover { background-color: #0e906f; }";
const QString HISTORY_LIST =
    "QListWidget { background-color: #EEEEEE; color: #333333; border: none; }"
    "QListWidget::item { padding: 10px; border-radius: 5px; margin: 2px 0px; }"
    "QListWidget::item:selected { background-color: #D0D0D0; }"
    "QListWidget::item:hover { background-color: #E0E0E0; }";
const QString BUTTON =
    "QPushButton { background-color: transparent; color: #333333; "
    "border-radius: 5px; padding: 5px; text-align: left; }"
    "QPushButton:hover { background-color: #D0D0D0; }";
const QString SEND_BUTTON =
    "QPushButton { background-color: #10a37f; color: white; border-radius: "
    "4px; padding: 8px 16px; font-weight: bold; }"
    "QPushButton:hover { background-color: #0e906f; }";
} // namespace Style

// 设置UI组件
void UserChatWindow::setupUI() {
  // 基本窗口设置
  resize(1200, 800);
  setWindowTitle("AI助手聊天");
  setStyleSheet(Style::WINDOW);

  // 创建左侧布局
  QWidget *leftContainer = new QWidget(this);
  QVBoxLayout *leftLayout = new QVBoxLayout(leftContainer);
  leftLayout->setContentsMargins(10, 10, 10, 10);
  leftContainer->setStyleSheet(Style::LEFT_CONTAINER);
  leftContainer->setFixedWidth(250);

  // 添加标题和图标
  QLabel *titleLabel = new QLabel("Deepseek", this);
  titleLabel->setAlignment(Qt::AlignCenter);
  titleLabel->setStyleSheet(Style::TITLE);

  QIcon appIcon(":/resource/chatgpt-web/chatgpt.png");
  if (!appIcon.isNull()) {
    QHBoxLayout *titleLayout = new QHBoxLayout();
    QLabel *iconLabel = new QLabel();
    iconLabel->setPixmap(appIcon.pixmap(24, 24));
    titleLayout->addWidget(iconLabel);
    titleLayout->addWidget(titleLabel);
    titleLayout->setAlignment(Qt::AlignCenter);
    leftLayout->addLayout(titleLayout);
  } else {
    leftLayout->addWidget(titleLabel);
  }

  // 左侧控件
  newChatButton_ = new QPushButton("+ 新建会话", this);
  newChatButton_->setFixedHeight(40);
  newChatButton_->setStyleSheet(Style::NEW_CHAT_BUTTON);

  historyList_ = new QListWidget(this);
  historyList_->setStyleSheet(Style::HISTORY_LIST);

  // 底部按钮
  chatModeButton_ = new QPushButton("普通对话模式", this);
  chatModeButton_->setStyleSheet(Style::BUTTON);

  deleteChatButton_ = new QPushButton("删除当前会话", this);
  deleteChatButton_->setStyleSheet(Style::BUTTON);



  // 左侧布局添加控件
  leftLayout->addWidget(newChatButton_);
  leftLayout->addWidget(historyList_);

  QVBoxLayout *buttonsLayout = new QVBoxLayout();
  buttonsLayout->addWidget(chatModeButton_);
  buttonsLayout->addWidget(deleteChatButton_);
  leftLayout->addLayout(buttonsLayout);

  // 右侧聊天区域
  QWidget *rightContainer = new QWidget(this);
  QVBoxLayout *rightLayout = new QVBoxLayout(rightContainer);
  rightLayout->setContentsMargins(20, 20, 20, 20);
  rightContainer->setStyleSheet("background-color: white;");

  // 聊天显示区域
  chatScrollArea_ = new QScrollArea(this);
  chatScrollArea_->setWidgetResizable(true);
  chatScrollArea_->setFrameShape(QFrame::NoFrame);
  chatScrollArea_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  chatScrollArea_->setStyleSheet("background-color: white; border: none;");

  chatContentWidget_ = new QWidget();
  chatContentWidget_->setStyleSheet("background-color: white;");
  chatContentLayout_ = new QVBoxLayout(chatContentWidget_);
  chatContentLayout_->setAlignment(Qt::AlignTop);
  chatContentLayout_->setSpacing(0);
  chatContentLayout_->setContentsMargins(0, 0, 0, 20);

  chatScrollArea_->setWidget(chatContentWidget_);
  rightLayout->addWidget(chatScrollArea_, 1);

  // 底部输入区域
  QWidget *inputContainer = createInputArea();
  rightLayout->addWidget(inputContainer);

  // 主布局 - 拆分器
  QSplitter *splitter = new QSplitter(Qt::Horizontal, this);
  splitter->addWidget(leftContainer);
  splitter->addWidget(rightContainer);
  splitter->setStretchFactor(0, 1);
  splitter->setStretchFactor(1, 4);
  splitter->setHandleWidth(1);
  splitter->setStyleSheet("QSplitter::handle { background-color: #D0D0D0; }");

  // 设置整体布局
  QHBoxLayout *mainLayout = new QHBoxLayout(this);
  mainLayout->setContentsMargins(0, 0, 0, 0);
  mainLayout->setSpacing(0);
  mainLayout->addWidget(splitter);
  setLayout(mainLayout);

  // 添加欢迎信息
  QLabel *welcomeLabel =
      new QLabel("欢迎使用 Deepseek\n\n选择一个会话开始，或创建一个新的会话",
                 chatContentWidget_);
  welcomeLabel->setAlignment(Qt::AlignCenter);
  welcomeLabel->setStyleSheet("color: #888; font-size: 18px;");
  chatContentLayout_->addWidget(welcomeLabel);
  chatContentLayout_->setAlignment(welcomeLabel, Qt::AlignCenter);
}

// 创建输入区域的辅助方法
QWidget *UserChatWindow::createInputArea() {
  QWidget *inputContainer = new QWidget(this);
  inputContainer->setStyleSheet(
      "background-color: white; border-top: 1px solid #e5e5e5;");
  QVBoxLayout *inputLayout = new QVBoxLayout(inputContainer);
  inputLayout->setContentsMargins(0, 15, 0, 10);

  // 工具栏
  QHBoxLayout *toolbarLayout = new QHBoxLayout();
  toolbarLayout->setContentsMargins(0, 0, 0, 5);

  QPushButton *formatButton = new QPushButton("格式化", this);
  formatButton->setStyleSheet("QPushButton { background-color: transparent; "
                              "color: #666; border: none; }"
                              "QPushButton:hover { color: #10a37f; }");

  QPushButton *codeButton = new QPushButton("代码", this);
  codeButton->setStyleSheet("QPushButton { background-color: transparent; "
                            "color: #666; border: none; }"
                            "QPushButton:hover { color: #10a37f; }");

  toolbarLayout->addWidget(formatButton);
  toolbarLayout->addWidget(codeButton);
  toolbarLayout->addStretch();
  inputLayout->addLayout(toolbarLayout);

  // 输入框
  QWidget *textEditContainer = new QWidget(this);
  textEditContainer->setStyleSheet("border: 1px solid #e5e5e5; border-radius: "
                                   "8px; background-color: white;");
  QVBoxLayout *textEditLayout = new QVBoxLayout(textEditContainer);
  textEditLayout->setContentsMargins(2, 2, 2, 2);

  chatArea_ = new QTextEdit(this);
  chatArea_->setPlaceholderText("请输入您的问题...");
  chatArea_->setStyleSheet("QTextEdit { background-color: white; color: "
                           "#333333; border: none; padding: 10px; }");
  chatArea_->setMinimumHeight(50);
  chatArea_->setMaximumHeight(150);
  textEditLayout->addWidget(chatArea_);
  inputLayout->addWidget(textEditContainer);

  // 发送按钮
  QHBoxLayout *sendBtnLayout = new QHBoxLayout();
  sendBtnLayout->setContentsMargins(0, 8, 0, 0);
  sendBtnLayout->addStretch();

  QLabel *helpLabel = new QLabel("Shift + Enter 换行", this);
  helpLabel->setStyleSheet("color: #888; font-size: 12px;");

  sendButton_ = new QPushButton("发送", this);
  sendButton_->setStyleSheet(Style::SEND_BUTTON);
  sendButton_->setCursor(Qt::PointingHandCursor);

  sendBtnLayout->addWidget(helpLabel);
  sendBtnLayout->addWidget(sendButton_);
  inputLayout->addLayout(sendBtnLayout);

  return inputContainer;
}

// 设置信号和槽连接
void UserChatWindow::setupSignalsAndSlots() {
  connect(sendButton_, &QPushButton::clicked, this,
          &UserChatWindow::onSendButtonClicked);
  connect(newChatButton_, &QPushButton::clicked, this,
          &UserChatWindow::onNewChatClicked);
  connect(historyList_, &QListWidget::itemClicked, this,
          &UserChatWindow::onHistoryItemClicked);
  connect(deleteChatButton_, &QPushButton::clicked, this,
          &UserChatWindow::onDeleteChatClicked);
  connect(chatModeButton_, &QPushButton::clicked, this,
          &UserChatWindow::toggleChatMode);

  // 自动调整输入框高度
  connect(chatArea_, &QTextEdit::textChanged, [this]() {
    int docHeight = chatArea_->document()->size().toSize().height();
    int newHeight = qMin(docHeight + 20, 200);
    if (newHeight != chatArea_->height() && newHeight >= 100) {
      chatArea_->setFixedHeight(newHeight);
    }
  });
}

void UserChatWindow::setupChatHistory() {
  // 加载聊天图标
  QIcon chatIcon(":/resource/chatgpt-web/chatgpt.png");
  if (chatIcon.isNull()) {
    // 图标加载失败，使用默认图标
    chatIcon = style()->standardIcon(QStyle::SP_MessageBoxQuestion);
  }

  historyList_->setIconSize(QSize(24, 24));

  // 设置列表支持右键菜单
  historyList_->setContextMenuPolicy(Qt::CustomContextMenu);
  connect(historyList_, &QListWidget::customContextMenuRequested, this,
          &UserChatWindow::showHistoryContextMenu);
}

//添加消息到聊天的方法
void UserChatWindow::addMessageToChat(const QString &content,
                                      const QString &role) {
  if (currentChatIndex_ < 0 || currentChatIndex_ >= chatSessions_.size()) {
    return;
  }

  // 添加消息到当前会话
  ChatMessage message;
  message.role = role;
  message.content = content;
  message.time = getCurrentTimeString();

  chatSessions_[currentChatIndex_].messages.append(message);

  addMessageWidget(message);

  // 保存会话（现在是保存到用户特定的目录中）
  saveChats();
}

// 添加单个消息小部件的函数
void UserChatWindow::addMessageWidget(const ChatMessage &message) {
  // 不处理系统消息
  if (message.role == "system") {
    return;
  }

  // 创建消息容器
  QWidget *messageContainer = new QWidget();
  messageContainer->setStyleSheet(message.role == "user"
                                      ? "background-color: #ffffff;"
                                      : "background-color: #f7f7f8;");

  QHBoxLayout *messageLayout = new QHBoxLayout(messageContainer);
  messageLayout->setContentsMargins(20, 15, 20, 15);

  // 创建头像标签
  QLabel *avatarLabel = new QLabel();
  avatarLabel->setFixedSize(36, 36);

  // 设置头像样式和内容
  QPixmap avatar;
  if (message.role == "user") {
    avatar = QPixmap(":/resource/img/avatar.svg");
  } else {
    avatar = QPixmap(":/resource/chatgpt-web/chatgpt.png");
  }

  // 如果加载失败，创建默认头像
  if (avatar.isNull()) {
    avatar = QPixmap(36, 36);
    avatar.fill(QColor("#10a37f"));

    // 在头像上添加文字
    QPainter painter(&avatar);
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 16, QFont::Bold));
    painter.drawText(avatar.rect(), Qt::AlignCenter,
                     message.role == "user" ? "U" : "AI");
  }

  avatarLabel->setPixmap(
      avatar.scaled(36, 36, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  avatarLabel->setStyleSheet("border-radius: 18px; background-color: #f0f0f0;");
  messageLayout->addWidget(avatarLabel, 0, Qt::AlignTop);

  // 创建消息内容区
  QWidget *contentContainer = new QWidget();
  QVBoxLayout *contentLayout = new QVBoxLayout(contentContainer);
  contentLayout->setContentsMargins(15, 0, 15, 0);

  // 创建角色标签
  QLabel *roleLabel = new QLabel(message.role == "user" ? "用户" : "AI助手");
  roleLabel->setStyleSheet("font-weight: bold; color: #333333;");

  // 创建消息文本
  QTextBrowser *contentLabel = new QTextBrowser();
  contentLabel->setOpenExternalLinks(true);
  contentLabel->setFrameShape(QFrame::NoFrame);
  contentLabel->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  contentLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
  contentLabel->setStyleSheet("QTextBrowser { background-color: transparent; "
                              "color: #333333; border: none; }");

  // 处理消息内容
  QString htmlContent = message.content;
  htmlContent = formatMessageContent(htmlContent);

  // 设置内容
  contentLabel->setHtml(htmlContent);

  // 调整大小
  contentLabel->document()->adjustSize();
  contentLabel->setMinimumHeight(
      static_cast<int>(contentLabel->document()->size().height()));

  // 时间标签
  QLabel *timeLabel = new QLabel(message.time);
  timeLabel->setStyleSheet("color: #888888; font-size: 11px;");

  // 添加到布局
  contentLayout->addWidget(roleLabel);
  contentLayout->addWidget(contentLabel);
  contentLayout->addWidget(timeLabel, 0, Qt::AlignRight);

  // 添加内容容器到消息布局
  messageLayout->addWidget(contentContainer, 1);
  chatContentLayout_->addWidget(messageContainer);

  // 滚动到最新消息
  QScrollBar *scrollBar = chatScrollArea_->verticalScrollBar();
  QTimer::singleShot(
      100, [scrollBar]() { scrollBar->setValue(scrollBar->maximum()); });
}

// 格式化消息内容，处理代码块和其他格式
QString UserChatWindow::formatMessageContent(const QString &content) {
  QString htmlContent = content;

  // 处理代码块
  QRegExp codeBlockRegExp("```([\\s\\S]*?)```");
  int pos = 0;
  while ((pos = codeBlockRegExp.indexIn(htmlContent, pos)) != -1) {
    QString codeContent = codeBlockRegExp.cap(1);
    QString replacement =
        "<pre style='background-color: #f0f0f0; padding: 10px; "
        "border-radius: 5px; font-family: monospace; white-space: pre-wrap;'>" +
        codeContent.toHtmlEscaped() + "</pre>";
    htmlContent.replace(pos, codeBlockRegExp.matchedLength(), replacement);
    pos += replacement.length();
  }

  // 处理行内代码
  QRegExp inlineCodeRegExp("`([^`]+)`");
  pos = 0;
  while ((pos = inlineCodeRegExp.indexIn(htmlContent, pos)) != -1) {
    QString codeContent = inlineCodeRegExp.cap(1);
    QString replacement =
        "<code style='background-color: #f0f0f0; padding: 2px 4px; "
        "border-radius: 3px; font-family: monospace;'>" +
        codeContent.toHtmlEscaped() + "</code>";
    htmlContent.replace(pos, inlineCodeRegExp.matchedLength(), replacement);
    pos += replacement.length();
  }

  // 处理换行
  htmlContent.replace("\n", "<br>");

  return htmlContent;
}

QString UserChatWindow::getCurrentTimeString() const {
  return QDateTime::currentDateTime().toString("yyyy年MM月dd日 hh:mm");
}

void UserChatWindow::onSendButtonClicked() {
  QString userText = chatArea_->toPlainText().trimmed();
  if (userText.isEmpty()) {
    return;
  }

  // 清空输入框
  chatArea_->clear();

  // 添加用户消息到聊天记录
  addMessageToChat(userText, "user");

  // 显示等待状态
  QWidget *waitingWidget = createWaitingIndicator();
  chatContentLayout_->addWidget(waitingWidget);

  // 滚动到最新消息
  QScrollBar *scrollBar = chatScrollArea_->verticalScrollBar();
  scrollBar->setValue(scrollBar->maximum());

  // 处理API请求
  std::string prompt;
  // 检查是否有系统消息
  if (chatSessions_[currentChatIndex_].messages.size() > 0 &&
      chatSessions_[currentChatIndex_].messages[0].role == "system") {
    // 如果第一条消息是系统消息，在第一次用户输入时添加系统提示
    if (chatSessions_[currentChatIndex_].messages.size() <=
        3) { // 如果只有系统消息、欢迎消息和这次用户消息
      prompt =
          chatSessions_[currentChatIndex_].messages[0].content.toStdString() +
          "\n";
      prompt += "用户: " + userText.toStdString();
    } else {
      // 否则使用常规的提示生成
      prompt = preparePrompt(userText);
    }
  } else {
    // 没有系统消息，使用常规的提示生成
    prompt = preparePrompt(userText);
  }

  // 记录用户与AI对话的日志
  if (!userId_.isEmpty()) {
    tools::Logger::getInstance().log(
        tools::Logger::LogType::USER_CHAT, userId_.toStdString(),
        "用户发送消息: " + userText.left(50).toStdString() +
            (userText.length() > 50 ? "..." : ""));
  }

  // 调用API
  setCursor(Qt::BusyCursor);
  std::string response = dcall_.call_api(prompt);
  setCursor(Qt::ArrowCursor);

  // 记录AI响应的日志
  if (!userId_.isEmpty()) {
    std::string shortResponse = response.substr(0, 50);
    if (response.length() > 50) {
      shortResponse += "...";
    }

    tools::Logger::getInstance().log(tools::Logger::LogType::USER_CHAT,
                                     userId_.toStdString(),
                                     "AI响应: " + shortResponse);
  }

  // 移除等待提示
  removeWaitingIndicator();

  // 转换并显示AI回复
  std::string responseToHtml = markdownTohtml->act(response);
  addMessageToChat(QString::fromStdString(responseToHtml), "assistant");

  // 更新历史会话列表显示
  updateHistoryListItem();

  // 播放提示音
  QApplication::beep();
}

// 创建等待指示器小部件
QWidget *UserChatWindow::createWaitingIndicator() {
  QWidget *waitingWidget = new QWidget();
  waitingWidget->setStyleSheet("background-color: #f7f7f8;");
  QHBoxLayout *waitingLayout = new QHBoxLayout(waitingWidget);

  // AI头像
  QLabel *aiAvatarLabel = new QLabel();
  aiAvatarLabel->setFixedSize(36, 36);
  QPixmap aiAvatar(":/resource/chatgpt-web/chatgpt.png");
  if (aiAvatar.isNull()) {
    aiAvatar = QPixmap(36, 36);
    aiAvatar.fill(QColor("#10a37f"));
    QPainter painter(&aiAvatar);
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 16, QFont::Bold));
    painter.drawText(aiAvatar.rect(), Qt::AlignCenter, "AI");
  }
  aiAvatarLabel->setPixmap(
      aiAvatar.scaled(36, 36, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  aiAvatarLabel->setStyleSheet(
      "border-radius: 18px; background-color: #f0f0f0;");

  // 加载动画
  QLabel *waitingLabel = new QLabel("AI正在思考...");
  waitingLabel->setStyleSheet("color: #666666; font-style: italic;");

  // 布局
  waitingLayout->addWidget(aiAvatarLabel, 0, Qt::AlignTop);
  waitingLayout->addWidget(waitingLabel, 1, Qt::AlignVCenter);
  waitingLayout->addStretch();

  return waitingWidget;
}

// 移除等待指示器
void UserChatWindow::removeWaitingIndicator() {
  QLayoutItem *item =
      chatContentLayout_->takeAt(chatContentLayout_->count() - 1);
  if (item) {
    if (QWidget *widget = item->widget()) {
      delete widget;
    }
    delete item;
  }
}

// 准备API请求的提示文本
std::string UserChatWindow::preparePrompt(const QString &userText) {
  // 如果不是连续模式，直接返回用户输入
  if (!continuousMode_ ||
      chatSessions_[currentChatIndex_].messages.size() <= 1) {
    return userText.toStdString();
  }

  // 构建完整上下文，最多取最近10条消息
  std::string contextPrompt = "";
  int startIdx = qMax(0, chatSessions_[currentChatIndex_].messages.size() - 10);
  for (int i = startIdx;
       i < chatSessions_[currentChatIndex_].messages.size() - 1; i++) {
    const ChatMessage &msg = chatSessions_[currentChatIndex_].messages[i];
    if (msg.role == "user") {
      contextPrompt += "用户: " + msg.content.toStdString() + "\n";
    } else if (msg.role == "assistant") {
      contextPrompt += "AI: " + msg.content.toStdString() + "\n";
    }
  }
  contextPrompt += "用户: " + userText.toStdString();

  return contextPrompt;
}

// 更新历史列表项
void UserChatWindow::updateHistoryListItem() {
  int idx = historyList_->currentRow();
  if (idx >= 0) {
    QListWidgetItem *listItem = historyList_->item(idx);
    if (listItem) {
      QString name = chatSessions_[currentChatIndex_].name;
      int msgCount = chatSessions_[currentChatIndex_].messages.size();
      listItem->setText(name +
                        QString(" [%1]").arg(msgCount / 2)); // 每问答算一轮
    }
  }
}

void UserChatWindow::onNewChatClicked() {
  // 弹出对话框让用户输入会话名称
  bool ok;
  QString defaultName =
      QString("新对话 %1")
          .arg(QDateTime::currentDateTime().toString("MM-dd hh:mm"));
  QString chatName = QInputDialog::getText(this, "创建新会话",
                                           "请输入会话名称:", QLineEdit::Normal,
                                           defaultName, &ok);

  // 如果用户取消，不创建新会话
  if (!ok) {
    return;
  }

  // 如果用户未输入名称，使用默认名称
  if (chatName.isEmpty()) {
    chatName = defaultName;
  }

  qDebug() << "创建新的聊天会话:" << chatName;

  // 创建新会话
  ChatSession newSession;
  newSession.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
  newSession.name = chatName;
  newSession.isSelected = true;

  qDebug() << "用户ID:" << this->userId_;
  managerSystem::user currentUser(this->userId_.toStdString());

  // 构建系统提示框架
  std::string systemPrompt = "<系统角色>\n"
                             "您是高考志愿规划专家，需严格遵循以下规则：\n"
                             "1. 分析时优先考虑用户档案数据\n"
                             "2. 专业推荐必须关联选科组合\n"
                             "3. 每次响应必须包含风险提示\n"
                             "</系统角色>\n\n";

  // 用户档案区块
  systemPrompt += "<用户档案>\n";
  systemPrompt += "姓名: " + currentUser.get_user_name() + "\n";
  systemPrompt += "省份: " + currentUser.get_user_province() + "\n";
  systemPrompt += "分数: " + currentUser.get_user_points() + "\n";
  // 目前选科信息是固定的
  systemPrompt += "选科: 物理、化学、生物\n";
  systemPrompt += "意向专业: " + currentUser.get_user_wants_major() + "\n";
  systemPrompt += "</用户档案>\n\n";
  qDebug() << "Hello" << QString::fromStdString(systemPrompt);
  // 动态指令注入
  systemPrompt += "<处理规则>\n";
  systemPrompt += "1. 必须列出3个专业细分方向\n"
                  "2. 要求用户确认具体方向\n"
                  "3. 比较各方向课程差异\n";
  systemPrompt += "1. 生成院校推荐列表（冲刺/稳妥/保底）\n"
                  "2. 显示近3年专业分数线趋势\n"
                  "3. 包含至少1个风险预警\n";
  systemPrompt += "<输出格式>\n"
                  "使用Markdown格式，包含：\n"
                  "- 等效分计算：原始分 + 年度系数\n"
                  "- 数据来源标注（如：教育部2024年数据）\n"
                  "- 使用emoji图标区分信息类型\n"
                  "</输出格式>\n\n";

  // 添加两条消息：系统消息和欢迎消息
  // 首先添加系统消息（用户看不见）
  ChatMessage systemMsg;
  systemMsg.role = "system";
  systemMsg.content = QString::fromStdString(systemPrompt);
  systemMsg.time = getCurrentTimeString();
  newSession.messages.append(systemMsg);

  // 添加欢迎消息
  ChatMessage welcomeMsg;
  welcomeMsg.role = "assistant";
  welcomeMsg.content = "您好，我是高考志愿规划专家。根据您的信息，我将为您提供"
                       "专业的高考志愿规划建议。请问您有什么具体问题需要咨询？";
  welcomeMsg.time = getCurrentTimeString();
  newSession.messages.append(welcomeMsg);

  // 取消之前会话的选中状态
  if (currentChatIndex_ >= 0 && currentChatIndex_ < chatSessions_.size()) {
    chatSessions_[currentChatIndex_].isSelected = false;
  }

  // 添加到会话列表
  chatSessions_.append(newSession);
  currentChatIndex_ = chatSessions_.size() - 1;

  // 更新UI
  QListWidgetItem *item = new QListWidgetItem(
      QIcon(":/resource/chatgpt-web/chatgpt.png"), chatName);
  historyList_->addItem(item);
  historyList_->setCurrentRow(historyList_->count() - 1);

  // 显示新会话
  displayCurrentChat();

  // 为当前用户创建新的聊天文件并保存会话
  if (!userId_.isEmpty()) {
    qDebug() << "用户ID存在，创建新的聊天文件:" << userId_;
    QString filePath = createNewSessionFile();
    if (!filePath.isEmpty()) {
      qDebug() << "成功创建新的聊天文件:" << filePath;
    } else {
      qWarning() << "创建新的聊天文件失败";
    }
  } else {
    qDebug() << "用户ID为空，不创建聊天文件";
  }

  // 保存会话
  saveChats();
}

void UserChatWindow::onHistoryItemClicked(QListWidgetItem *item) {
  int row = historyList_->row(item);
  if (row >= 0 && row < chatSessions_.size()) {
    // 更新当前会话索引
    if (currentChatIndex_ >= 0 && currentChatIndex_ < chatSessions_.size()) {
      chatSessions_[currentChatIndex_].isSelected = false;
    }
    currentChatIndex_ = row;
    chatSessions_[currentChatIndex_].isSelected = true;

    // 显示选中会话
    displayCurrentChat();
  }
}

void UserChatWindow::onDeleteChatClicked() {
  if (currentChatIndex_ < 0 || currentChatIndex_ >= chatSessions_.size()) {
    return;
  }

  QMessageBox::StandardButton reply;
  reply = QMessageBox::question(this, "确认删除",
                                "确定要删除当前会话吗？此操作不可恢复。",
                                QMessageBox::Yes | QMessageBox::No);

  if (reply == QMessageBox::Yes) {
    // 如果用户目录存在，删除对应的会话文件
    if (!userId_.isEmpty() && !userDirectory_.isEmpty()) {
      QString sessionId = chatSessions_[currentChatIndex_].id;
      QString sessionFilePath = userDirectory_ + "/" + sessionId + ".json";

      // 直接删除以会话ID命名的文件
      if (std::filesystem::exists(sessionFilePath.toStdString())) {
        try {
          std::filesystem::remove(sessionFilePath.toStdString());
          qDebug() << "成功删除会话文件:" << sessionFilePath;
        } catch (const std::exception &e) {
          qWarning() << "删除会话文件失败:" << e.what();
        }
      } else {
        // 兼容模式：搜索包含此会话ID的所有文件
        qDebug() << "会话文件不存在，尝试搜索包含此ID的文件:" << sessionId;
        std::string dirPath = userDirectory_.toStdString();
        if (std::filesystem::exists(dirPath)) {
          for (const auto &entry :
               std::filesystem::directory_iterator(dirPath)) {
            if (entry.is_regular_file() &&
                entry.path().extension() == ".json") {
              QString filePath = QString::fromStdString(entry.path().string());

              // 检查文件中是否包含此会话ID
              try {
                nlohmann::json fileJson;
                read_from_file(filePath.toStdString(), fileJson);
                if (fileJson.contains("id") &&
                    fileJson["id"].get<std::string>() ==
                        sessionId.toStdString()) {
                  // 找到对应文件，删除它
                  std::filesystem::remove(entry.path());
                  qDebug() << "找到并删除会话文件:" << filePath;
                  break;
                }
              } catch (const std::exception &e) {
                qWarning("读取会话文件失败: %s", e.what());
              }
            }
          }
        }
      }
    }

    // 删除当前会话
    QString deletedName = chatSessions_[currentChatIndex_].name;
    chatSessions_.removeAt(currentChatIndex_);
    delete historyList_->takeItem(currentChatIndex_);

    // 显示删除成功提示
    QMessageBox::information(this, "删除成功",
                             QString("已删除会话：%1").arg(deletedName));

    // 选择新的当前会话
    if (chatSessions_.isEmpty()) {
      // 如果没有会话了，创建一个新的
      currentChatIndex_ = -1;
      onNewChatClicked();
    } else {
      // 选择上一个会话
      currentChatIndex_ = qMin(currentChatIndex_, chatSessions_.size() - 1);
      historyList_->setCurrentRow(currentChatIndex_);
      chatSessions_[currentChatIndex_].isSelected = true;
      displayCurrentChat();
    }

    // 保存会话状态
    saveChats();
  }
}

void UserChatWindow::toggleChatMode() {
  continuousMode_ = !continuousMode_;
  if (continuousMode_) {
    chatModeButton_->setText("连续对话模式");
    chatModeButton_->setToolTip("当前为连续对话模式，AI会记住对话上下文");
    chatModeButton_->setStyleSheet(
        "QPushButton { background-color: #10a37f; color: white; border-radius: "
        "5px; padding: 5px; text-align: left; }"
        "QPushButton:hover { background-color: #0e906f; }");

    // 显示提示信息
    QMessageBox::information(
        this, "模式切换",
        "已切换到连续对话模式。\n\n"
        "在此模式下，AI会记住对话历史，您可以进行连续多轮对话。");
  } else {
    chatModeButton_->setText("普通对话模式");
    chatModeButton_->setToolTip("当前为普通对话模式，每次对话都是独立的");
    chatModeButton_->setStyleSheet(
        "QPushButton { background-color: transparent; color: #333333; "
        "border-radius: "
        "5px; padding: 5px; text-align: left; }"
        "QPushButton:hover { background-color: #D0D0D0; }");

    // 显示提示信息
    QMessageBox::information(
        this, "模式切换",
        "已切换到普通对话模式。\n\n"
        "在此模式下，AI不会记住对话历史，每次对话都是独立的。");
  }

  // 如果当前有会话，保存设置
  if (currentChatIndex_ >= 0 && currentChatIndex_ < chatSessions_.size()) {
    saveChats();
  }
}

void UserChatWindow::displayCurrentChat() {

  if (currentChatIndex_ < 0 || currentChatIndex_ >= chatSessions_.size()) {
    return;
  }

  // 清空当前显示
  while (QLayoutItem *item = chatContentLayout_->takeAt(0)) {
    if (QWidget *widget = item->widget()) {
      delete widget;
    }
    delete item;
  }

  // 显示当前会话的所有消息
  const ChatSession &session = chatSessions_[currentChatIndex_];

  // 更新左侧会话列表选中状态
  for (int i = 0; i < historyList_->count(); ++i) {
    QListWidgetItem *item = historyList_->item(i);
    if (i == currentChatIndex_) {
      item->setSelected(true);
    } else {
      item->setSelected(false);
    }
  }

  QString lastDate = "";

  // 会话为空时显示欢迎信息
  if (session.messages.isEmpty()) {
    QLabel *welcomeLabel =
        new QLabel("欢迎使用 DeepSeek\n\n开始一个新的对话", chatContentWidget_);
    welcomeLabel->setObjectName("welcomeLabel");
    welcomeLabel->setAlignment(Qt::AlignCenter);
    welcomeLabel->setStyleSheet("color: #888; font-size: 18px;");
    chatContentLayout_->addWidget(welcomeLabel);
    chatContentLayout_->setAlignment(welcomeLabel, Qt::AlignCenter);
    return;
  }

  // 显示当前会话的所有消息
  for (int i = 0; i < session.messages.size(); i++) {
    const ChatMessage &message = session.messages[i];

    // 跳过系统消息，不显示给用户
    if (message.role == "system") {
      continue;
    }

    // 检查是否需要添加日期分隔
    QString currDate = message.time.split(" ")[0]; // 取日期部分
    if (currDate != lastDate) {
      QWidget *dateWidget = new QWidget();
      dateWidget->setStyleSheet("background-color: transparent;");

      QHBoxLayout *dateLayout = new QHBoxLayout(dateWidget);
      dateLayout->setContentsMargins(10, 5, 10, 5);

      QFrame *leftLine = new QFrame();
      leftLine->setFrameShape(QFrame::HLine);
      leftLine->setFrameShadow(QFrame::Sunken);
      leftLine->setStyleSheet("background-color: #e5e5e5;");

      QLabel *dateLabel = new QLabel(currDate);
      dateLabel->setStyleSheet("color: #888888; padding: 0 10px;");

      QFrame *rightLine = new QFrame();
      rightLine->setFrameShape(QFrame::HLine);
      rightLine->setFrameShadow(QFrame::Sunken);
      rightLine->setStyleSheet("background-color: #e5e5e5;");

      dateLayout->addWidget(leftLine, 1);
      dateLayout->addWidget(dateLabel, 0);
      dateLayout->addWidget(rightLine, 1);

      chatContentLayout_->addWidget(dateWidget);
      lastDate = currDate;
    }

    // 使用新的消息小部件方法添加消息
    addMessageWidget(message);
  }

  // 添加弹性空间，使得内容靠上
  chatContentLayout_->addStretch();

  // 滚动到最新消息
  QScrollBar *scrollBar = chatScrollArea_->verticalScrollBar();
  QTimer::singleShot(
      100, [scrollBar]() { scrollBar->setValue(scrollBar->maximum()); });
}

void UserChatWindow::updateChatDisplay() { displayCurrentChat(); }

void UserChatWindow::saveChats() {
  // 如果用户ID为空，则不保存
  if (userId_.isEmpty()) {
    return;
  }

  // 确保用户目录存在
  initUserDirectory();

  // 遍历所有会话，为每个会话保存独立的文件
  for (int i = 0; i < chatSessions_.size(); i++) {
    const ChatSession &session = chatSessions_[i];

    // 构建会话JSON
    nlohmann::json sessionJson;
    sessionJson["id"] = session.id.toStdString();
    sessionJson["name"] = session.name.toStdString();
    sessionJson["selected"] = session.isSelected;

    // 添加更新时间戳
    QString timestamp =
        QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss");
    sessionJson["updated_at"] = timestamp.toStdString();

    // 添加创建时间戳（如果是新会话）
    if (!session.messages.isEmpty()) {
      // 使用第一条消息的时间作为创建时间
      sessionJson["created_at"] = session.messages.first().time.toStdString();
    } else {
      sessionJson["created_at"] = timestamp.toStdString();
    }

    // 添加消息
    nlohmann::json messagesJson = nlohmann::json::array();
    for (const ChatMessage &message : session.messages) {
      nlohmann::json messageJson;
      messageJson["role"] = message.role.toStdString();
      messageJson["content"] = message.content.toStdString();
      messageJson["time"] = message.time.toStdString();
      messagesJson.push_back(messageJson);
    }
    sessionJson["messages"] = messagesJson;

    // 构建文件名 (直接使用会话ID，不包含时间戳，便于更新)
    QString fileName = userDirectory_ + "/" + session.id + ".json";

    try {
      // 保存单个会话文件
      write_to_file(fileName.toStdString(), sessionJson);
    } catch (const std::exception &e) {
    }
  }

  // 保存用户配置信息(如连续对话模式)
  nlohmann::json userConfigJson;
  userConfigJson["continuous_mode"] = continuousMode_;
  userConfigJson["user_id"] = userId_.toStdString();
  userConfigJson["last_active"] = QDateTime::currentDateTime()
                                      .toString("yyyy-MM-dd hh:mm:ss")
                                      .toStdString();

  try {
    write_to_file(userDirectory_.toStdString() + "/user_config.json",
                  userConfigJson);
  } catch (const std::exception &e) {
    qWarning("保存用户配置失败: %s", e.what());
  }
}

void UserChatWindow::loadChats() {
  // 如果已经设置了用户ID，则跳过，因为会在loadUserSessions中加载
  if (!userId_.isEmpty()) {
    return;
  }

  try {
    nlohmann::json rootJson;
    read_from_file("resource/History/chat_history.json", rootJson);

    if (rootJson.contains("continuous_mode")) {
      continuousMode_ = rootJson["continuous_mode"].get<bool>();
      if (continuousMode_) {
        chatModeButton_->setText("当前为连续对话");
      } else {
        chatModeButton_->setText("当前为普通对话");
      }
    }

    if (rootJson.contains("chats") && rootJson["chats"].is_array()) {
      nlohmann::json chatsJson = rootJson["chats"];

      for (const auto &sessionJson : chatsJson) {
        ChatSession session;
        session.id =
            QString::fromStdString(sessionJson["id"].get<std::string>());
        session.name =
            QString::fromStdString(sessionJson["name"].get<std::string>());
        session.isSelected = sessionJson["selected"].get<bool>();

        if (sessionJson.contains("messages") &&
            sessionJson["messages"].is_array()) {
          for (const auto &messageJson : sessionJson["messages"]) {
            ChatMessage message;
            message.role =
                QString::fromStdString(messageJson["role"].get<std::string>());
            message.content = QString::fromStdString(
                messageJson["content"].get<std::string>());
            message.time =
                QString::fromStdString(messageJson["time"].get<std::string>());
            session.messages.append(message);
          }
        }

        chatSessions_.append(session);

        // 添加到UI列表
        QString displayName = session.name;
        if (session.messages.size() > 0) {
          displayName += QString(" [%1]").arg(session.messages.size() / 2);
        }
        QListWidgetItem *item = new QListWidgetItem(
            QIcon(":/resource/chatgpt-web/chatgpt.png"), displayName);
        historyList_->addItem(item);

        if (session.isSelected) {
          currentChatIndex_ = chatSessions_.size() - 1;
          historyList_->setCurrentRow(currentChatIndex_);
        }
      }
    }
  } catch (const std::exception &e) {
    qWarning("加载聊天记录失败: %s", e.what());
  }
}

// 构造函数
UserChatWindow::UserChatWindow(QWidget *parent) : QWidget(parent) {
  // 初始化Markdown转HTML的转换器
  markdownTohtml = std::make_shared<MarkdownTransHtml>();


  // 设置UI组件
  setupUI();
  setupChatHistory();
  setupSignalsAndSlots();

  // 此时userId_还未设置，登录后会调用setUserId方法
  // 然后加载对应用户的聊天记录

  // 设置焦点到输入区
  chatArea_->setFocus();
}

// 设置当前用户ID
void UserChatWindow::setUserId(const QString &userId) {
  userId_ = userId;
  initUserDirectory();
  loadUserSessions(); // 加载用户的所有聊天会话
}

// 初始化用户聊天目录
void UserChatWindow::initUserDirectory() {
  if (userId_.isEmpty()) {
    qDebug() << "用户ID:Empty, 无法初始化用户目录"; ;
    return;
  }

  // 设置基础历史文件夹路径
  std::string historyBasePath =
      "/home/ccy/code_workspace/cpp_finall/resource/History";
  std::filesystem::create_directories(historyBasePath);

  // 确保users子文件夹存在
  std::string usersPath = historyBasePath + "/users";
  std::filesystem::create_directories(usersPath);

  // 构建用户目录路径 (History/users/用户ID/)
  userDirectory_ = QString::fromStdString(usersPath) + "/" + userId_;

  // 创建目录结构
  std::string dirPath = userDirectory_.toStdString();
  bool success = std::filesystem::create_directories(dirPath);
  qDebug() << "用户目录创建结果:" << success;
}

// 创建新的聊天会话文件
QString UserChatWindow::createNewSessionFile() {
  if (userId_.isEmpty()) {
    return QString();
  }

  // 确保目录存在
  initUserDirectory();

  // 生成新的会话ID和当前时间戳
  QString timestamp =
      QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
  QString sessionId = QUuid::createUuid().toString(QUuid::WithoutBraces);
  QString filename = userDirectory_ + "/" + sessionId + ".json";

  // 创建基础结构并保存
  nlohmann::json sessionJson;
  sessionJson["id"] = sessionId.toStdString();
  sessionJson["name"] =
      QString("新对话 %1")
          .arg(QDateTime::currentDateTime().toString("MM-dd hh:mm"))
          .toStdString();
  sessionJson["messages"] = nlohmann::json::array();
  sessionJson["created_at"] = timestamp.toStdString();
  sessionJson["updated_at"] = timestamp.toStdString();

  try {
    // 保存文件
    write_to_file(filename.toStdString(), sessionJson);
  } catch (const std::exception &e) {
    return QString();
  }

  return filename;
}

// 加载用户的所有聊天会话
void UserChatWindow::loadUserSessions() {
  if (userId_.isEmpty()) {
    return;
  }

  if (userDirectory_.isEmpty()) {
    return;
  }

  // 清空现有会话列表
  historyList_->clear();
  chatSessions_.clear();
  currentChatIndex_ = -1;

  std::string dirPath = userDirectory_.toStdString();

  // 检查目录是否存在
  if (!std::filesystem::exists(dirPath)) {
    // 创建用户目录并开始新会话
    initUserDirectory();
    onNewChatClicked();
    return;
  }

  // 收集所有会话文件及其更新时间
  struct SessionFileInfo {
    QString filePath;      // 文件完整路径
    QString id;            // 会话ID
    QDateTime updatedTime; // 更新时间
  };
  QVector<SessionFileInfo> sessionFiles;

  try {
    // 遍历用户目录下的所有JSON文件
    for (const auto &entry : std::filesystem::directory_iterator(dirPath)) {
      if (entry.is_regular_file() && entry.path().extension() == ".json") {
        QString filePath = QString::fromStdString(entry.path().string());
        QString fileName =
            QString::fromStdString(entry.path().filename().string());

        // 跳过用户配置文件
        if (fileName == "user_config.json") {
          continue;
        }

        try {
          // 读取会话文件
          nlohmann::json sessionJson;
          read_from_file(filePath.toStdString(), sessionJson);

          // 提取会话ID
          QString sessionId;
          if (sessionJson.contains("id")) {
            sessionId =
                QString::fromStdString(sessionJson["id"].get<std::string>());
          } else {
            // 如果文件中没有ID，使用文件名（不含扩展名）作为ID
            sessionId = fileName.split(".").first();
          }

          // 提取更新时间
          QDateTime updatedTime;
          if (sessionJson.contains("updated_at")) {
            QString timeStr = QString::fromStdString(
                sessionJson["updated_at"].get<std::string>());
            updatedTime = QDateTime::fromString(timeStr, "yyyy-MM-dd hh:mm:ss");
            if (!updatedTime.isValid()) {
              // 尝试其他格式
              updatedTime = QDateTime::fromString(timeStr, "yyyyMMdd_hhmmss");
            }
          }

          // 如果更新时间无效，使用文件修改时间
          if (!updatedTime.isValid()) {
            auto fileTime = std::filesystem::last_write_time(entry.path());
            auto sctp = std::chrono::time_point_cast<
                std::chrono::system_clock::duration>(
                fileTime - std::filesystem::file_time_type::clock::now() +
                std::chrono::system_clock::now());
            auto time_t = std::chrono::system_clock::to_time_t(sctp);
            updatedTime = QDateTime::fromSecsSinceEpoch(time_t);
          }

          // 添加到文件列表
          sessionFiles.append({filePath, sessionId, updatedTime});
        } catch (const std::exception &e) {
        }
      }
    }
  } catch (const std::exception &e) {
  }

  // 按更新时间排序（最新的在前）
  std::sort(sessionFiles.begin(), sessionFiles.end(),
            [](const auto &a, const auto &b) {
              return a.updatedTime > b.updatedTime;
            });

  // 加载每个会话文件
  for (const auto &fileInfo : sessionFiles) {
    const QString &filePath = fileInfo.filePath;
    nlohmann::json sessionJson;

    try {
      qDebug() << "加载会话文件:" << filePath;
      read_from_file(filePath.toStdString(), sessionJson);

      if (sessionJson.contains("id") && sessionJson.contains("name")) {
        ChatSession session;
        session.id =
            QString::fromStdString(sessionJson["id"].get<std::string>());
        session.name =
            QString::fromStdString(sessionJson["name"].get<std::string>());
        session.isSelected = false;

        // 加载消息
        if (sessionJson.contains("messages") &&
            sessionJson["messages"].is_array()) {
          for (const auto &msgJson : sessionJson["messages"]) {
            if (msgJson.contains("role") && msgJson.contains("content") &&
                msgJson.contains("time")) {
              ChatMessage message;
              message.role =
                  QString::fromStdString(msgJson["role"].get<std::string>());
              message.content =
                  QString::fromStdString(msgJson["content"].get<std::string>());
              message.time =
                  QString::fromStdString(msgJson["time"].get<std::string>());
              session.messages.append(message);
            }
          }
        }

        chatSessions_.append(session);

        // 构建显示名称
        QString displayName = session.name;

        // 计算对话轮次
        int conversationRounds = session.messages.size() / 2;

        // 取会话的第一条用户消息作为摘要
        QString summary;
        for (const auto &msg : session.messages) {
          if (msg.role == "user") {
            // 截取用户输入的前20个字符作为摘要
            summary = msg.content.left(20);
            if (msg.content.length() > 20) {
              summary += "...";
            }
            break;
          }
        }

        // 构建显示名称：会话名称 [对话轮次] - 会话摘要
        if (conversationRounds > 0) {
          displayName += QString(" [%1]").arg(conversationRounds);

          if (!summary.isEmpty()) {
            displayName += " - " + summary;
          }
        }

        // 创建列表项并设置工具提示
        QListWidgetItem *item = new QListWidgetItem(
            QIcon(":/resource/chatgpt-web/chatgpt.png"), displayName);

        // 设置工具提示显示更多信息
        QString tooltip = session.name + "\n";
        // 如果有消息，显示第一条消息的时间
        if (!session.messages.isEmpty()) {
          tooltip +=
              QString("创建时间: %1\n").arg(session.messages.first().time);
        } else if (sessionJson.contains("created_at")) {
          tooltip += QString("创建时间: %1\n")
                         .arg(QString::fromStdString(
                             sessionJson["created_at"].get<std::string>()));
        }
        tooltip += QString("对话轮次: %1").arg(conversationRounds);
        if (!summary.isEmpty()) {
          tooltip += "\n首次提问: " + summary;
        }
        item->setToolTip(tooltip);

        historyList_->addItem(item);
      }
    } catch (const std::exception &e) {
      qWarning() << "处理会话文件时出错:" << filePath << e.what();
    }
  }

  // 加载用户配置
  try {
    QString configPath = userDirectory_ + "/user_config.json";
    if (std::filesystem::exists(configPath.toStdString())) {
      nlohmann::json configJson;
      read_from_file(configPath.toStdString(), configJson);

      // 加载连续对话模式设置
      if (configJson.contains("continuous_mode")) {
        continuousMode_ = configJson["continuous_mode"].get<bool>();
        if (continuousMode_) {
          chatModeButton_->setText("连续对话模式");
          chatModeButton_->setStyleSheet(
              "QPushButton { background-color: #10a37f; color: white; "
              "border-radius: "
              "5px; padding: 5px; text-align: left; }"
              "QPushButton:hover { background-color: #0e906f; }");
        } else {
          chatModeButton_->setText("普通对话模式");
          chatModeButton_->setStyleSheet(
              "QPushButton { background-color: transparent; color: #333333; "
              "border-radius: 5px; padding: 5px; text-align: left; }"
              "QPushButton:hover { background-color: #D0D0D0; }");
        }
      }
    }
  } catch (const std::exception &e) {
    qWarning() << "加载用户配置时出错:" << e.what();
  }

  // 如果有会话，显示最新的会话
  if (!chatSessions_.isEmpty()) {
    currentChatIndex_ = 0; // 第一个是最新的
    chatSessions_[currentChatIndex_].isSelected = true;

    // 更新UI
    historyList_->setCurrentRow(currentChatIndex_);
    historyList_->update();

    // 显示当前聊天
    qDebug() << "显示当前聊天";
    displayCurrentChat();
  } else {
    // 如果没有会话，创建一个新的
    qDebug() << "没有找到会话，创建新会话";
    onNewChatClicked();
  }
}

// 显示历史会话右键菜单
void UserChatWindow::showHistoryContextMenu(const QPoint &pos) {
  // 获取点击的项目
  QListWidgetItem *item = historyList_->itemAt(pos);
  if (!item)
    return;

  // 创建右键菜单
  QMenu contextMenu(this);

  // 添加菜单项
  QAction *renameAction =
      contextMenu.addAction(QIcon::fromTheme("edit-rename"), "重命名");
  QAction *exportAction =
      contextMenu.addAction(QIcon::fromTheme("document-save"), "导出会话");
  QAction *deleteAction =
      contextMenu.addAction(QIcon::fromTheme("edit-delete"), "删除会话");

  // 添加分隔符
  contextMenu.addSeparator();

  // 添加导入功能
  QAction *importAction =
      contextMenu.addAction(QIcon::fromTheme("document-open"), "导入会话");

  // 显示菜单并获取选择的操作
  QAction *selectedAction = contextMenu.exec(historyList_->mapToGlobal(pos));

  if (selectedAction == renameAction) {
    // 设置当前索引并执行重命名
    int row = historyList_->row(item);
    if (row >= 0 && row < chatSessions_.size()) {
      currentChatIndex_ = row;
      renameChatSession();
    }
  } else if (selectedAction == exportAction) {
    // 设置当前索引并执行导出
    int row = historyList_->row(item);
    if (row >= 0 && row < chatSessions_.size()) {
      currentChatIndex_ = row;
      exportChatSession();
    }
  } else if (selectedAction == deleteAction) {
    // 设置当前索引并执行删除
    int row = historyList_->row(item);
    if (row >= 0 && row < chatSessions_.size()) {
      currentChatIndex_ = row;
      onDeleteChatClicked();
    }
  } else if (selectedAction == importAction) {
    importChatSessions();
  }
}


// 重命名当前选中的聊天会话
void UserChatWindow::renameChatSession() {
  if (currentChatIndex_ < 0 || currentChatIndex_ >= chatSessions_.size()) {
    return;
  }

  bool ok;
  QString oldName = chatSessions_[currentChatIndex_].name;
  QString newName = QInputDialog::getText(
      this, "重命名对话", "请输入新的对话名称:", QLineEdit::Normal, oldName,
      &ok);

  if (ok && !newName.isEmpty()) {
    // 更新会话名称
    chatSessions_[currentChatIndex_].name = newName;

    // 更新列表显示
    QListWidgetItem *item = historyList_->item(currentChatIndex_);
    if (item) {
      // 保留消息计数部分
      QString currentText = item->text();
      int bracketPos = currentText.indexOf(" [");

      if (bracketPos > 0) {
        // 保留消息数量部分，更新名称部分
        item->setText(newName + currentText.mid(bracketPos));
      } else {
        item->setText(newName);
      }

      // 更新工具提示
      QString tooltip = item->toolTip();
      tooltip.replace(oldName, newName);
      item->setToolTip(tooltip);
    }

    // 保存更改
    saveChats();
  }
}

// 导出当前选中的会话到文件
void UserChatWindow::exportChatSession() {
  if (currentChatIndex_ < 0 || currentChatIndex_ >= chatSessions_.size()) {
    return;
  }

  // 获取保存文件路径
  QString defaultName =
      chatSessions_[currentChatIndex_].name.replace(" ", "_") + "_export.json";
  QString filePath = QFileDialog::getSaveFileName(this, "导出会话", defaultName,
                                                  "JSON文件 (*.json)");

  if (filePath.isEmpty()) {
    return;
  }

  // 创建JSON数据
  nlohmann::json sessionJson;
  const ChatSession &session = chatSessions_[currentChatIndex_];

  sessionJson["id"] = session.id.toStdString();
  sessionJson["name"] = session.name.toStdString();
  sessionJson["selected"] = session.isSelected;
  sessionJson["timestamp"] =
      QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss").toStdString();

  // 添加消息
  nlohmann::json messagesJson = nlohmann::json::array();
  for (const ChatMessage &message : session.messages) {
    nlohmann::json messageJson;
    messageJson["role"] = message.role.toStdString();
    messageJson["content"] = message.content.toStdString();
    messageJson["time"] = message.time.toStdString();
    messagesJson.push_back(messageJson);
  }
  sessionJson["messages"] = messagesJson;

  // 保存文件
  try {
    write_to_file(filePath.toStdString(), sessionJson);
    QMessageBox::information(this, "导出成功",
                             "会话已成功导出到:\n" + filePath);
  } catch (const std::exception &e) {
    QMessageBox::critical(this, "导出失败",
                          QString("导出会话失败: %1").arg(e.what()));
  }
}

// 导入会话记录
void UserChatWindow::importChatSessions() {
  // 如果用户ID为空，无法导入
  if (userId_.isEmpty()) {
    QMessageBox::warning(this, "导入失败", "请先登录一个用户账号");
    return;
  }

  // 获取要导入的文件
  QStringList filePaths = QFileDialog::getOpenFileNames(
      this, "选择要导入的会话文件", "", "JSON文件 (*.json)");

  if (filePaths.isEmpty()) {
    return;
  }

  int importCount = 0;

  // 确保用户目录存在
  initUserDirectory();

  // 导入每个文件
  for (const QString &importPath : filePaths) {
    try {
      // 读取导入文件
      nlohmann::json importJson;
      read_from_file(importPath.toStdString(), importJson);

      // 检查文件格式是否正确
      if (!importJson.contains("name")) {
        QMessageBox::warning(this, "格式错误",
                             "文件格式不正确: " + importPath +
                                 "\n缺少必要字段 'name'");
        continue;
      }

      // 确保messages字段存在
      if (!importJson.contains("messages")) {
        importJson["messages"] = nlohmann::json::array();
      }

      // 生成新的会话ID
      QString sessionId = QUuid::createUuid().toString(QUuid::WithoutBraces);

      // 添加/更新时间戳信息
      QString currentTime =
          QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
      importJson["id"] = sessionId.toStdString();
      importJson["created_at"] = currentTime.toStdString();
      importJson["updated_at"] = currentTime.toStdString();
      importJson["selected"] = false;

      // 使用会话ID作为文件名
      QString newFilePath = userDirectory_ + "/" + sessionId + ".json";

      // 保存文件
      write_to_file(newFilePath.toStdString(), importJson);
      importCount++;

      qDebug() << "成功导入会话:"
               << QString::fromStdString(importJson["name"].get<std::string>())
               << "到文件:" << newFilePath;

    } catch (const std::exception &e) {
      qWarning() << "导入文件失败:" << importPath << e.what();
      QMessageBox::warning(this, "导入失败",
                           "导入文件失败: " + importPath +
                               "\n错误: " + e.what());
    }
  }

  if (importCount > 0) {
    QMessageBox::information(
        this, "导入成功",
        QString("成功导入 %1 个会话。\n正在重新加载会话列表...")
            .arg(importCount));

    // 重新加载会话列表
    loadUserSessions();
  } else {
    QMessageBox::warning(this, "导入结果", "没有成功导入任何会话");
  }
}
